import { promisify } from "../../libs/util";
import Peripheral from "../Peripheral";
import { ab2hex, str2ab } from "../../libs/util";
import phera from "../../const/phera";
import { okmsg, failmsg } from "../../const/msg";
import { create } from "domain";
import { readcmd } from "./const";

/**
 * 心电血压仪
 */
class BPMonitor extends Peripheral {

  async start() {
    return promisify(phera.openBluetoothAdapter)();
  }

  notifyDeviceFound() {
    phera.onBluetoothDeviceFound(async (res) => {
      console.log('[onBluetoothDeviceFound]', res);

      const devices = res.devices;
      if (!Array.isArray(devices)) return;

      for (let deviceItem of devices) {
        const { RSSI, advertisData, deviceId } = deviceItem;
        const localName = deviceItem.localName || deviceItem.name;

        if (localName.indexOf('700X-000') > -1) {
          await this.stopDiscovery();
          this.createConnect(deviceId);
        }
      }
    });
  }

  async createConnect(deviceId) {
    const connectRes = await this.connect(deviceId);
    console.log('[createConnect#createBLEConnection]', connectRes);

    const servicesRes = await promisify(phera.getBLEDeviceServices)({ deviceId });
    console.log('[createConnect#getBLEDeviceServices]\n', deviceId, servicesRes);
    const serviceId = servicesRes.services.find(v => v.isPrimary).uuid;
    this.serviceId = serviceId;

    const characterRes = await promisify(phera.getBLEDeviceCharacteristics)({ deviceId, serviceId });
    console.log('[createConnect#getBLEDeviceCharacteristics]', characterRes);

    for (let item of characterRes.characteristics) {
      if (item.properties.read) {//该特征值是否支持 read 操作
        this.readCharacteristicId = item.uuid;
      }
      if (item.properties.write) {
        this.writeCharacteristicId = item.uuid;
      }
      if (item.properties.notify || item.properties.indicate) {//该特征值是否支持 notify或indicate 操作
        this.notifyCharacteristicId = item.uuid;
      }
    }

    const { readCharacteristicId } = this.getCurrentServices();
    
    this.notifyCharacteristicValueChange();

    return promisify(phera.notifyBLECharacteristicValueChange)({
      state: true, // 启用 notify 功能
      deviceId,
      serviceId,
      characteristicId: readCharacteristicId
    });
  }

  getCurrentServices() {
    const { serviceId, readCharacteristicId, writeCharacteristicId, notifyCharacteristicId } = this;
    return { serviceId, readCharacteristicId, writeCharacteristicId, notifyCharacteristicId };
  }

  notifyCharacteristicValueChange() {
    /* if (this._initedNotifyCharacterist) {
      return;
    }
    this._initedNotifyCharacterist = true; */

    let seq = 0;
    phera.onBLECharacteristicValueChange(async ({ deviceId, value }) => {
      const arr = new Uint8Array(value); //Uint8Array
      console.log(`[notifyCharacteristicValueChange#Change]`, deviceId, arr);

      const arrI = new Int8Array(arr);
      const format = arr[1];

      if (arr[0] - seq != 1 && arr[0] - seq != -255) {
        console.log('**************************');
      }
      seq = arr[0];

      switch (format) {
        case readcmd.BT_MEASURE:
          this.didUpdateMeasure(arr);
          break;
        case readcmd.BT_HEADER:
          this.didUpdateHeader(arr);
          break;
        default:
          break;
      }
    });
  }


  didUpdateMeasure(arr) {
    console.log('[didUpdateMeasure]');
  }

  didUpdateHeader(arr) {
    console.log('[didUpdateHeader]');
  }


}

export default BPMonitor;
